<template>
  <view class="foodPage d-flex flex-column bg-light">
    <StatusBar></StatusBar>
    <view class="p-2 d-flex align-items-center border">
      <view class="ratio ratio-1x1" style="height:6rem;width: 6rem">
        <image :src="store.img" class="rounded-circle"/>
      </view>
      <view>
        <text class="mx-2 text-center h1 fw-bold">{{ store.name }}</text>
        <view class="mx-2 text-secondary">
          {{ store.address }}
        </view>
        <view class="mx-2 text-secondary">{{ store.phone }}</view>
      </view>
    </view>
    <view id="mainScroll" class="d-flex flex-grow-1 overflow-scroll">
      <!-- 左侧菜单 -->
      <scroll-view id="leftScroll" scroll-y :scroll-top="leftTop" @scroll="onScrollLeft"
                   class="col-3 h-100 overflow-y-scroll border-end">
        <view id="leftBox" class="h-100">
          <view v-for="(category, index) in categories" :key="index"
                @click="onMenuItemClick(category,index)"
                class="py-3 menu-item text-center " :class="{ 'active': selectedIndex === index }">
            {{ category.label }}
          </view>
        </view>
      </scroll-view>
      <!-- 右侧内容 -->
      <scroll-view id="rightScroll" scroll-y enable-flex :scroll-top="rightTop" :scroll-into-view="rightScrollIntoView"
                   @scroll="onScrollRight" class="col-9 h-100 overflow-y-auto">
        <view id="rightBox" class="p-2">
          <view v-for="(category, menuIndex) in categories" :key="menuIndex" class="type"
                :id="'rightScrollIntoView_'+category.id">
            <view class="text-secondary">
              {{ category.label }}
            </view>
            <view v-for="(food, itemIndex) in category.goods" :key="itemIndex" class="my-2 d-flex">
              <view class="ratio ratio-1x1" style="width: 6rem">
                <image :src=food.image alt="加载失败"/>
              </view>
              <view class="ms-2 mt-1 flex-grow-1 d-flex flex-column">
                <view class="fw-bold">{{ food.name }}</view>
                <view class="mt-1 text-secondary">{{ food.describe }}</view>
                <view class="mt-auto d-flex justify-content-between">
                  <view class="text-danger">¥{{ food.price }}</view>
                  <view class="d-flex justify-content-center align-items-center">
                    <image src="/static/img/减.svg" v-if="food.num>0" @click="handleChange(food,-1)"
                           class="mx-2 rounded-circle" style="width: 1.2rem;height: 1.2rem"></image>
                    <text v-if="food.num>0" class="mx-1 ">{{ food.num }}</text>
                    <image src="/static/img/加.svg" @click="handleChange(food,1)"
                           class="mx-2 rounded-circle" style="width: 1.2rem;height: 1.2rem"></image>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="position-relative px-4 mt-1 d-flex align-items-center border-top">
      <view @click="openCart" class="d-flex align-items-center">
        <uni-badge class="uni-badge-left-margin d-flex align-items-center" :text="orderList.length" absolute="rightTop"
                   size="small">
          <image src="/static/img/购物车.svg" style="width: 3rem;height: 3rem"></image>
        </uni-badge>
        <view class="ms-3 fw-bold">
          ¥{{ totalMoney }}
        </view>
      </view>
      <button @click="pickOver" :disabled="orderList.length===0"
              class="ms-auto p-2 text-black fw-bold border rounded rounded-2 bg-danger">
        选好了
      </button>
      <view v-if="showOrderList"
            class="position-absolute start-0 bottom-100 w-100 p-2 overflow-scroll border border-2 bg-light"
            style="max-height: 40vh;">
        <scroll-view :scroll-y="true" class="h-100">
          <view v-for="(item, index) in orderList" :key="index" class="p-1 d-flex align-items-center border-bottom">
            <image :src="item.image" style="width: 3rem;height: 3rem"></image>
            <text class="ms-2">{{ item.name }}</text>
            <text class="ms-3">¥{{ item.price }}</text>
            <view class="ms-auto d-flex justify-content-center align-items-center">
              <image src="/static/img/减.svg" v-if="item.num>0" @click="handleChange(item,-1)"
                     class="mx-2 rounded-circle" style="width: 1.2rem;height: 1.2rem"></image>
              <text v-if="item.num>0" class="mx-1 ">{{ item.num }}</text>
              <image src="/static/img/加.svg" @click="handleChange(item,1)"
                     class="mx-2 rounded-circle" style="width: 1.2rem;height: 1.2rem"></image>
            </view>
          </view>
          <view v-if="orderList.length===0" class="text-center">
            还没有添加商品
          </view>
        </scroll-view>
      </view>
    </view>

  </view>
</template>

<script>
import {getJson, postJson} from "../../api/http";
import {goodsCategories, OrderApi} from "../../api/api";
import StatusBar from "../component/StatusBar.vue";

export default {
  name: "OrderInfo",
  components: {
    StatusBar,
  },
  data() {
    return {
      selectedIndex: 0,
      leftBox: 0,
      rightScrollIntoView: "",
      leftTop: 0,
      rightTop: 0,
      touchFlag: 0,
      categories: [],
      menuHeight: 0,

      orderList: [],
      typeList: [],
      store: {
        name: "爱好吃",
        address: "深圳市南山区深南大道爱好吃",
        img: "https://ggok.top/api/file/FileApi2/bee745629ad011efa0c40242ac110007.jpeg",
        phone: "18812341234",
        onlineStart: "08:00",
        onlineEnd: "20:00",
      },
      showOrderList: false

    }
  },
  computed: {
    totalMoney() {
      if (this.orderList.length === 0) {
        return 0
      }
      return this.orderList.map(value => value.price * value.num).reduce((a, b) => a + b)
    },
  },
  methods: {
    async init() {
      let data = {
        order_code: this.order_code
      }
      let res = await getJson(goodsCategories, data)
      if (res.code !== 1) {
        this.$message.error('服务器异常');
        return
      }
      res.data.forEach(v => v.goods.forEach(v2 => v2.num = 0))
      this.categories = res.data
      // 数据加载完成后，等待DOM更新
      this.$nextTick(() => {
        uni.createSelectorQuery().selectAll('.type').boundingClientRect(rects => {
          console.log("onShow  type", rects)
          this.typeList = rects
        }).exec();
      });
    },
    handleChange(item, value) {
      console.log("handleChange", item, item?.num)
      if (item.num === undefined) {
        item.num = 0
      }
      item.num = item.num + value
      if (item.num > 0 && this.orderList.indexOf(item) === -1) {
        this.orderList.push(item)
      }
      this.orderList = this.orderList.filter(v => v.num > 0)
    },
    onMenuItemClick(category, index) {
      console.log("click", category, index)
      this.selectedIndex = index
      this.rightScrollIntoView = 'rightScrollIntoView_' + category.id;
    },
    onScrollLeft(e) {
      console.log("onScrollLeft", e)
    },
    onScrollRight(e) {
      console.log("onScrollRight", e)
      let total = 0
      for (let i = 0; i < this.typeList.length; i++) {
        total += this.typeList[i].height
        if (total > e.detail.scrollTop + this.menuHeight) {
          this.selectedIndex = i
          this.leftTop = this.leftBox * (i / this.typeList.length)
          break
        }
      }
    },
    async orderFood() {
      let data = {
        info_list: this.orderList
      }
      let res = await postJson(OrderApi + "/0", data)
      if (res !== 1) {
        uni.showToast({
          title: '操作失败,请稍后再试',
          icon: 'none',
          duration: 3000
        });
      }
    },
    async pickOver() {
      await this.orderFood()
      this.orderList.forEach(value => {
        value.num = 0
      })
      await uni.reLaunch({
        url: '/pages/MyOrder',
      });
    },
    openCart() {
      this.showOrderList = !this.showOrderList;
    },
  },
  created() {
    this.init()
  },
  onReady() {
    // 获取购物车内容高度并滚动到顶部
    uni.createSelectorQuery().select('#mainScroll').boundingClientRect(rect => {
      this.menuHeight = Math.ceil(rect.height)
    }).exec();
    uni.createSelectorQuery().select('#leftScroll').boundingClientRect(rect => {
      console.log("onShow-leftScroll", rect.height, rect)
    }).exec();
    uni.createSelectorQuery().select('#leftBox').boundingClientRect(rect => {
      console.log("onShow-leftBox", rect.height, rect)
      this.leftBox = rect.height // 取消
    }).exec();
    uni.createSelectorQuery().select('#rightScroll').boundingClientRect(rect => {
      console.log("onShow-rightScroll", rect.height, rect)
    }).exec();
    uni.createSelectorQuery().select('#rightBox').boundingClientRect(rect => {
      console.log("onShow-rightBox", rect.height, rect)
    }).exec();
  }
}
</script>

<style scoped lang="less">
.foodPage {
  height: calc(100vh);
  /*#ifdef H5 */
  height: calc(100vh - var(--window-top) - 100rpx);
  /* #endif */
  // display: flex;
  // flex-direction: column;
  //background-color: pink;
}

.active {
  background-color: white;
  font-weight: bold;
  border-left: green solid .25rem;
}

.menu-item {
  border-bottom: 1px solid #eee;
}

.menu-item:last-child {
  border-bottom: none;
}
</style>